<?php

namespace addons\fastflow\library\aliyunsms;

class AliyunSms
{
    private $smsconfig;
    private $domain;
    private $accessKeySecret;

    /**
     * AliyunSms constructor.
     * @param $accessKeyId 申请开通的ID
     * @param $accessKeySecret 申请开通的密匙
     * @param $signName 签名
     * @param $templateCode 模板代码
     * @param $templateParam 模板参数
     * @param $domain 域名
     */
    public function __construct($accessKeyId, $accessKeySecret, $signName, $templateCode, $templateParam, $domain)
    {
        $this->smsconfig = [
            // AccessKey ID
            "AccessKeyId"      => $accessKeyId,
            // 签名
            "SignName"         => $signName,
            // 消息模板
            "TemplateCode"     => $templateCode,
            // 模板参数
            "TemplateParam"    => $templateParam,
            // 返回格式
            'Format'           => 'JSON',
            // 版本号
            'Version'          => '2017-05-25',
            // 签名版本
            'SignatureVersion' => '1.0',
            // 加密方式
            'SignatureMethod'  => 'HMAC-SHA1',
            // 接口参数
            'Action'           => 'SendSms',
        ];
        $this->domain = "http://" . $domain . '?';
        $this->accessKeySecret = $accessKeySecret;
    }

    /**
     * 处理编码
     * @param $str
     * @return mixed|string
     */
    private function percentEncode($str)
    {
        // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    /**
     * 签名
     * @param $parameters
     * @param $accessKeySecret
     * @return string
     */
    private function computeSignature($parameters)
    {
        // 将参数Key按字典顺序排序
        ksort($parameters);
        // 生成规范化请求字符串
        $canonicalizedQueryString = '';
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
        }
        // 生成用于计算签名的字符串 stringToSign
        $stringToSign = "GET&%2F&" . $this->percentencode(substr($canonicalizedQueryString, 1));
        // 计算签名，注意accessKeySecret后面要加上字符'&'
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $this->accessKeySecret . '&', true));
        return $signature;
    }

    /**
     * CURL请求
     * @param $url
     * @return mixed|string
     */
    private function https_request($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return ['code' => 0, 'msg' => curl_error($curl)];
        }
        curl_close($curl);
        return $data;
    }

    public function sendSms($phoneNumbers)
    {
        $this->smsconfig['PhoneNumbers'] = $phoneNumbers;
        $this->smsconfig['SignatureNonce'] = uniqid();
        $this->smsconfig['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
        $this->smsconfig['Signature'] = $this->computeSignature($this->smsconfig);
        // 发送请求
        $result = $this->https_request($this->domain . http_build_query($this->smsconfig));
        return json_decode($result, true);
    }

}
